//
//  AppDelegate.swift
//  weibo_swift
//
//  Created by dulinlong on 15/6/23.
//  Copyright © 2015年 sheji_56. All rights reserved.
//

///App Key：2806351036
///App Secret：9f5b30f039cdc1426c758af23ebb7c87
///https://api.weibo.com/oauth2/authorize?client_id=2806351036&redirect_uri=http://www.baidu.com
///
///https://www.baidu.com/?code=3e10f950c225fdd285fe8f5a2b5246d9
///
///https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.00h6_THG5GKvDD305480a2361jssQB
import UIKit
import AFNetworking
//全局账户
var sharedUserAccount = UserAccount.loadAccount()

let SwitchRootControllerNotification = "SwitchRootControllerNotification"


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        //设置网络
        setupNetWork()
        //设置外观
        setupAppearance()
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.rootViewController = defaultViewController()
        window?.makeKeyAndVisible()
        
        //注册控制器切换通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: SwitchRootControllerNotification, object: nil)
        
        return true
    }
    
    func switchViewController(notifacation: NSNotification){
      let isMainVC = notifacation.object as! Bool
        window?.rootViewController = isMainVC ? MainViewController() : WelcomeViewController()
    }
    
///  默认显示的控制器
    func defaultViewController() -> UIViewController{
        if sharedUserAccount != nil {
          return  self.isNewUpdate() ? NewFeatureViewController() : WelcomeViewController()
        }
        return MainViewController()
    }
    
///  检测版本更新
    func isNewUpdate() -> Bool{
        // 1. 获取当前版本信息
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let version = Double(currentVersion) ?? 0
       
        // 2.获取沙盒版本信息
        let versionKey = "versionKey"
        let sandVersion = NSUserDefaults.standardUserDefaults().doubleForKey(versionKey)
        
        //3.将版本写入沙盒
        NSUserDefaults.standardUserDefaults().setDouble(version, forKey: versionKey)
        
        return version > sandVersion
    }
    
///  设置全局外观
    private func setupAppearance(){
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }
    
///  设置网络访问
    private func setupNetWork(){
        //设置缓存大小
        let cache = NSURLCache(memoryCapacity: 4*1024*1024, diskCapacity: 20*1024*1024, diskPath: nil)
        NSURLCache.setSharedURLCache(cache)
        //设置指示器
        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
    }

}

